<?php
/**
 * Created by PhpStorm.
 * User: huanglinjie
 * Date: 2019/1/9
 * Time: 11:56 AM
 */
namespace app\util;

use app\common\exception\ApiException;
use think\Db;
use think\Log;

class Tools {
    /**
     * 两个高精度数计算
     * @param float $left
     * @param float $right
     * @param float $scale 精确到的小数点位数
     */
    public static function bcCalculate($left, $right, $type, $scale = 2) {
        bcscale($scale);
        switch ($type) {
            case '+' :
                $return = bcadd($left,$right);
                break;
            case '-' :
                $return = bcsub($left,$right);
                break;
            case '*' :
                $return = bcmul($left,$right);
                break;
            case '/' :
                $return = bcdiv($left,$right);
                break;
            default :
                throw new ApiException('计算参数不合法', 200, -1);
        }
        return $return;
    }

    /*
    * 后台登录密码加密
    * */
    public static function UserpasswordMd5($password) {
        return md5(config("app.AUTH_KEY") . $password);
    }

    /*
     * 后台登录密码加密
     * */
    public static function passwordMd5($password) {
        return md5(config("apiAdmin.AUTH_KEY") . $password);
    }

    /*
     * 代理登录密码加密
     * */
    public static function AgentPasswordMd5($password) {
        return md5(config("app.AGENT_KEY") . $password);
    }

    /*
     * 支付密码加密
     * */
    public static function payPasswordMd5($payPassword) {
        if (strlen($payPassword) != 6 ) {
            $payPassword = (new Aes())->decrypt($payPassword);
        }
        return md5(sha1($payPassword . config('app.MASTER_PAY_PASSWORD_SALT')));
    }

    /*
     * 商户支付密码加密
     * */
    public static function MasterpayPasswordMd5($payPassword) {
        return md5(sha1($payPassword . config('app.PAY_PASSWORD_SALT')));
    }


    /**
     * 判断当前用户是否是超级管理员
     * @param string $uid
     * @return bool
     */
    public static function isAdministrator($uid = '') {
        if (!empty($uid)) {
            $adminConf = config('apiAdmin.USER_ADMINISTRATOR');
            if (is_array($adminConf)) {
                if (is_array($uid)) {
                    $m = array_intersect($adminConf, $uid);
                    if (count($m)) {
                        return true;
                    }
                } else {
                    if (in_array($uid, $adminConf)) {
                        return true;
                    }
                }
            } else {
                if (is_array($uid)) {
                    if (in_array($adminConf, $uid)) {
                        return true;
                    }
                } else {
                    if ($uid == $adminConf) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 将查询的二维对象转换成二维数组
     * @param array $res
     * @param string $key 允许指定索引值
     * @return array
     */
    public static function buildArrFromObj($res, $key = '') {
        $arr = [];
        foreach ($res as $value) {
            $value = $value->toArray();
            if ($key) {
                $arr[$value[$key]] = $value;
            } else {
                $arr[] = $value;
            }
        }

        return $arr;
    }

    /**
     * 将二维数组变成指定key
     * @param $array
     * @param $keyName
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     * @return array
     */
    public static function buildArrByNewKey($array, $keyName = 'id') {
        $list = array();
        foreach ($array as $item) {
            $list[$item[$keyName]] = $item;
        }
        return $list;
    }

    /**
     * 获取13位时间戳
     * @return int
     */
    public static function get13TimeStamp() {
        list($t1, $t2) = explode(' ', microtime());
        return $t2 . ceil($t1 * 1000);
    }
    public static function curlGet($url,$httpHeader = []){
        $ch = curl_init();

        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        if (!empty($httpHeader)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//绕过ssl验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        //执行并获取HTML文档内容
        $output = curl_exec($ch);

        //释放curl句柄
        curl_close($ch);
        return $output;
    }
    /**
     * curl-post请求
     * @param $url
     * @param $data
     * @return mixed
     */
    public static function curlPost($url,$data,$httpHeader = []){ // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        if (!empty($httpHeader)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $httpHeader);
        }
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        //curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            Log::write('Errno：'.curl_error($curl), 'curl');
            throw new ApiException(curl_error($curl), 200, -1);
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式
    }

    /**
     * 返回值处理
     * @param $code
     * @param $msg
     * @param array $data
     * @return array
     */
    public static function buildReturn($code, $msg, $data = []) {
        $return = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];
        return $return;
    }

    /*
    * @name 生成32位系统订单号
    * @return string
    */
    public static function orderNo(){
        // 密码字符集，可任意添加你需要的字符
        $chars = '0123456789'.time();
        $str = '';
        $length = 14;
        for ( $i = 0; $i < $length; $i++ ) {
            $str .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }
        $orderNO = 'DHMAC'.time().$str.'P';
        return $orderNO;
    }

    /*
   * @name 生成32位系统订单号
   * @return string
   */
    public static function orderNoTotal(){
        // 密码字符集，可任意添加你需要的字符
        $chars = '0123456789'.time();
        $str = '';
        $length = 14;
        for ( $i = 0; $i < $length; $i++ ) {
            $str .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }
        $orderNO = 'TOTAL'.time().$str.'P';
        return $orderNO;
    }

    /*
   * @name 生成32位系统订单号
   * @return string
   */
    public static function orderNoAuction(){
        // 密码字符集，可任意添加你需要的字符
        $chars = '0123456789'.time();
        $str = '';
        $length = 14;
        for ( $i = 0; $i < $length; $i++ ) {
            $str .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }
        $orderNO = 'AUC'.time().$str.'P';
        return $orderNO;
    }

    /*
    * @name 核销码生成
    */
    public static function verificationCode() {
        $orderSn = substr(time(), 3,8) .sprintf('%03d', rand(0,999));
        return $orderSn;
    }

    public static function randString( $length = 22 ) {
        // 密码字符集，可任意添加你需要的字符
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $password = time();
        for ( $i = 0; $i < $length; $i++ )
        {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
            $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }
        return md5($password) ;
    }

    //随机数生成
    public static function token_create($length = 32) {
        $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
        $key = '';
        for ($i = 0; $i < $length; $i++) {
            $key .= $pattern{mt_rand(0, 61)};    //生成php随机数
        }
        return $key;
    }

    //终端IP获取
    public static function get_client_ip($type = 0) {
        $type       =  $type ? 1 : 0;
        $ip         =   'unknown';
        if ($ip !== 'unknown') return $ip[$type];
        if(isset($_SERVER['HTTP_X_REAL_IP'])){//nginx 代理模式下，获取客户端真实IP
            $ip=$_SERVER['HTTP_X_REAL_IP'];
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {//客户端的ip
            $ip     =   $_SERVER['HTTP_CLIENT_IP'];
        }elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {//浏览当前页面的用户计算机的网关
            $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos    =   array_search('unknown',$arr);
            if(false !== $pos) unset($arr[$pos]);
            $ip     =   trim($arr[0]);
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];//浏览当前页面的用户计算机的ip地址
        }else{
            $ip=$_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u",ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }
    /*
     * 数组转xml
     * */
    public static function arrayToXml($arr){
        $xml = "<xml>";
        foreach ($arr as $key=>$val){
            if(is_array($val)){
                $xml.="<".$key.">".self::arrayToXml($val)."</".$key.">";
            }else{
                $xml.="<".$key.">".$val."</".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }

    /*
     * xml转数组
     * */
    public static function xmltoarray($xml) {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $val = json_decode(json_encode($xmlstring),true);
        return $val;
    }

    /**
     * 获取客户端系统
     */
    public static function getOS() {
        $ua = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($ua, 'Android') !== false) {
            return 'Android';
        } elseif (strpos($ua, 'iPhone') !== false) {
            return 'IOS';
        } else{
            return 'other';
        }
    }

    /**
     * 处理手机号中间为隐藏 * 号
     */
    public static function mobileDispose($tel) {
        $new_tel1 = substr($tel, 0, 3).'****'.substr($tel, 7);
        return $new_tel1;
    }

    /**
     *微信签名
     */
    public static function wxSign($options) {
        ksort($options);
        $signature = http_build_query($options);
        $signature = urldecode($signature);

        $signature = strtoupper(md5($signature . '&key=' . config('pament.wechat_key')));
        return $signature;
    }

    /**
     *计算某个经纬度的周围某段距离的正方形的四个点
     *
     *@param lng float 经度
     *@param lat float 纬度
     *@return array 正方形的四个点的经纬度坐标
     */
    public static function returnSquarePoint($lng, $lat){
        $distance = 500;//float 该点所在圆的半径，该圆与此正方形内切，单位公里
        $earth_radius = 6378.137;//地球半径，平均半径为6378.137km
        $dlng =  2 * asin(sin($distance / (2 * $earth_radius)) / cos(deg2rad($lat)));
        $dlng = rad2deg($dlng);  //转换弧度

        $dlat = $distance/$earth_radius;
        $dlat = rad2deg($dlat);
        return array(
            'leftTop'=>array('lat'=>$lat + $dlat,'lng'=>$lng-$dlng),
            'rightTop'=>array('lat'=>$lat + $dlat, 'lng'=>$lng + $dlng),
            'leftBottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng - $dlng),
            'rightBottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng + $dlng)
        );
    }

    /**
     * 将银行卡中间八个字符隐藏为*
     */
    public static function getHideBankCardNum($bankaccount) {
        $new_bankaccount = substr($bankaccount, 0, 3).'********'.substr($bankaccount, 11);
        return $new_bankaccount;
    }

    /*
    * 获取随机价格
    *@param $min 最低价格（元）
    *@param $max 最高价格（元）
    * */
    public static function randomPrice($min = 0, $max = 1) {
        $price = mt_rand($min * 100, $max * 100);
        $price = bcdiv($price, 100, 2);
        return $price;
    }

    /*
     * 获取会员等级
     * */
    public static function getUserClass($AllMoney) {
        $arr = config('app.USER_CLASS');
        $num  = 0 ;
        foreach ($arr as $k => $val){
            if($AllMoney >= $val ){
                $num = $k;
            }
        }
        return $num;
    }

    public static function mobileType() {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (stripos($user_agent, "iPhone")!==false) {
            $brand = 'iPhone';
        } else if (stripos($user_agent, "SAMSUNG")!==false || stripos($user_agent, "Galaxy")!==false || strpos($user_agent, "GT-")!==false || strpos($user_agent, "SCH-")!==false || strpos($user_agent, "SM-")!==false) {
            $brand = '三星';
        } else if (stripos($user_agent, "Huawei")!==false || stripos($user_agent, "Honor")!==false || stripos($user_agent, "H60-")!==false || stripos($user_agent, "H30-")!==false) {
            $brand = '华为';
        } else if (stripos($user_agent, "Lenovo")!==false) {
            $brand = '联想';
        } else if (strpos($user_agent, "MI-ONE")!==false || strpos($user_agent, "MI 1S")!==false || strpos($user_agent, "MI 2")!==false || strpos($user_agent, "MI 3")!==false || strpos($user_agent, "MI 4")!==false || strpos($user_agent, "MI-4")!==false) {
            $brand = '小米';
        } else if (strpos($user_agent, "HM NOTE")!==false || strpos($user_agent, "HM201")!==false) {
            $brand = '红米';
        } else if (stripos($user_agent, "Coolpad")!==false || strpos($user_agent, "8190Q")!==false || strpos($user_agent, "5910")!==false) {
            $brand = '酷派';
        } else if (stripos($user_agent, "ZTE")!==false || stripos($user_agent, "X9180")!==false || stripos($user_agent, "N9180")!==false || stripos($user_agent, "U9180")!==false) {
            $brand = '中兴';
        } else if (stripos($user_agent, "OPPO")!==false || strpos($user_agent, "X9007")!==false || strpos($user_agent, "X907")!==false || strpos($user_agent, "X909")!==false || strpos($user_agent, "R831S")!==false || strpos($user_agent, "R827T")!==false || strpos($user_agent, "R821T")!==false || strpos($user_agent, "R811")!==false || strpos($user_agent, "R2017")!==false) {
            $brand = 'OPPO';
        } else if (strpos($user_agent, "HTC")!==false || stripos($user_agent, "Desire")!==false) {
            $brand = 'HTC';
        } else if (stripos($user_agent, "vivo")!==false) {
            $brand = 'vivo';
        } else if (stripos($user_agent, "K-Touch")!==false) {
            $brand = '天语';
        } else if (stripos($user_agent, "Nubia")!==false || stripos($user_agent, "NX50")!==false || stripos($user_agent, "NX40")!==false) {
            $brand = '努比亚';
        } else if (strpos($user_agent, "M045")!==false || strpos($user_agent, "M032")!==false || strpos($user_agent, "M355")!==false) {
            $brand = '魅族';
        } else if (stripos($user_agent, "DOOV")!==false) {
            $brand = '朵唯';
        } else if (stripos($user_agent, "GFIVE")!==false) {
            $brand = '基伍';
        } else if (stripos($user_agent, "Gionee")!==false || strpos($user_agent, "GN")!==false) {
            $brand = '金立';
        } else if (stripos($user_agent, "HS-U")!==false || stripos($user_agent, "HS-E")!==false) {
            $brand = '海信';
        } else if (stripos($user_agent, "Nokia")!==false) {
            $brand = '诺基亚';
        } else {
            $brand = '其他手机';
        }
        return $brand;
    }


    public static function ip(){
        $ip_long = array(
            array('607649792', '608174079'), // 36.56.0.0-36.63.255.255
            array('1038614528', '1039007743'), // 61.232.0.0-61.237.255.255
            array('1783627776', '1784676351'), // 106.80.0.0-106.95.255.255
            array('2035023872', '2035154943'), // 121.76.0.0-121.77.255.255
            array('2078801920', '2079064063'), // 123.232.0.0-123.235.255.255
            array('-1950089216', '-1948778497'), // 139.196.0.0-139.215.255.255
            array('-1425539072', '-1425014785'), // 171.8.0.0-171.15.255.255
            array('-1236271104', '-1235419137'), // 182.80.0.0-182.92.255.255
            array('-770113536', '-768606209'), // 210.25.0.0-210.47.255.255
            array('-569376768', '-564133889'), // 222.16.0.0-222.95.255.255
        );
        $rand_key = mt_rand(0, 9);
        return $ip = long2ip(mt_rand($ip_long[$rand_key][0], $ip_long[$rand_key][1]));
    }

    public static function storeVerificationCode(){
        //A-2020年标示
        $code = 'A' . substr(time(), 2) . sprintf('%04d', rand(0,9999));
        return $code;
    }


    public static function verificodeHandle($str){
        //通过正则，第一位字母与之后每四位截取到数组中
        preg_match('/([a-zA-Z]{1})([\d]{4})([\d]{4})([\d]{0,})?/', $str, $match);
        $str = '';print_r($match);
        unset($match[0]); //去除掉第一个键
        //通过循环，将字符串进行拼接并加入空格
        foreach ($match as $vo) {
            $str .= $vo . ' ';
        }
        return $str;
    }

    //无限级分类
    static function makeTree($list,$pk='id',$pid='pid',$child='child',$root=0){
        $tree=array();
        foreach($list as $key=> $val){
            if($val[$pid]==$root){
                //获取当前$pid所有子类
                    unset($list[$key]);
                    if(! empty($list)){
                        $childList = self::makeTree($list,$pk,$pid,$child,$val[$pk]); //来来来 找北京的子栏目 递归 空

                        if(!empty($childList)){
                            $val[$child]=$childList;
                        }
                    }
                    $tree[]=$val;
            }
        }
        return $tree;
    }

    /**
     * 清除到店订单支付过期时间
     * @param string $start 开始时间
     * @param string $now_time 当前时间
     * @return bool
     */
    public static function  getSaleStatus($start, $now_time){
        if($now_time<$start){
            $sale_status = 1;
        }else{
            $sale_status = 2;
        }
        return $sale_status;
    }

    /*
   * @name 生成32位系统订单号
   * @return string
   */
    public static function getCodeRed(){
        $d = substr(base_convert(md5(uniqid(md5(microtime(true)),true)), 16, 10), 0, 8);
        $w['codeRed'] = $d;
        $user_info = Db::name('user_deposit')->field("*")->where($w)->find();
        if ($user_info) {
            self::getCodeRed();
        }
        return $d;
    }

}
